package mwa.cs.admin.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.SMMappingDAO;
import mwa.cs.database.Database;
import mwa.cs.model.SMRole;
import mwa.cs.model.SmMapping;
import mwa.cs.model.SmPackage;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS89001Srvl
 */
public class CS89001Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Database db;
	private String vapackageID;
	private String vaAgentBrowser;
	private String vaUrlAddress;
	private int vnUserId;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS89001Srvl() {
        super();
      
    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	String process_type = request.getParameter("process_type");
    	vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
    
		if(process_type != null && process_type.equals("insert")){ 
			 insert(request,response);	
		}else if(process_type != null && process_type.equals("getDataTable")){
			getDataTable(request,response);
		}else{
			getDataFromPackge(request,response);
		}
    }
    
    public void insert(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter out = response.getWriter();
		
		String voMenuId[] = request.getParameterValues("checkbox_menuId[]");
		String vaRoleId = request.getParameter("vaRoleId");
		this.db = new Database();
		
		try{
			db.beginTransaction();	
			
			SMMappingDAO daoMappingDAO = new SMMappingDAO(db);
			daoMappingDAO.deletemunuIdByRoleId(vapackageID, vaRoleId);
			
			for(int i=0;i<voMenuId.length;i++){
						String vaMenuId = voMenuId[i];
						boolean vbParse = true;
						try {
							int vnTemp = Integer.parseInt(vaMenuId);
						} catch (Exception e) {
							vbParse = false;
						}
						if ( vbParse == true){
							SmMapping poSmMapping = new SmMapping();
							poSmMapping.setVaPackageId(vapackageID);
							poSmMapping.setVaMenuId(vaMenuId);
							poSmMapping.setVaRoleId(vaRoleId);
							poSmMapping.setVnInsertUserId(vnUserId);
							poSmMapping.setVaInsertDate(JDate.getDate());
							poSmMapping.setVaInsertTime(JDate.getTime());
							poSmMapping.setVnUpdateUserId(vnUserId);
							poSmMapping.setVaUpdateDate(JDate.getDate());
							poSmMapping.setVaUpdateTime(JDate.getTime());												
							daoMappingDAO.insertMenuId(poSmMapping);
							response.getWriter().write("update_success");
						}
			}
			// set SMRole
			SMRole poSmRole = new SMRole();
			poSmRole.setVaStatus("Y");
			poSmRole.setVaUpdateDate(JDate.getDate());
			poSmRole.setVaUpdateTime(JDate.getTime());
			daoMappingDAO.updateStatusRole(vaRoleId, poSmRole);		
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS89001", JDate.getDate(), JDate.getTime(),vnUserId, "CS89001Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
		}finally{
			db.close();
		}
    }
    
    
    public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter out = response.getWriter();
		this.db = new Database();
		
			SMMappingDAO daoMappingDAO = new SMMappingDAO(db);
			String vaRoleId = request.getParameter("roleId");
			
			vapackageID = daoMappingDAO.getPackageIdBySiteId(vaRoleId);
			List<Map<String , Object>> listMenubyRole;
			List<Map<String , Object>> listMenuInRole;
			
			listMenubyRole = daoMappingDAO.getRoleMenu(vapackageID);
			listMenuInRole = daoMappingDAO.getMenuIdByRole(vapackageID, vaRoleId);
			
			for(int i = 0; i < listMenubyRole.size() ; i++){ 
				Map<String , Object> mapItem = (Map<String , Object>) listMenubyRole.get(i);
				Map<String , Object> mapItemRole = (Map<String , Object>) listMenuInRole.get(i);
				voColumn = new JSONArray();
				voColumn.add(mapItemRole.get("RESULT"));
				voColumn.add(mapItem.get("MENU_NAME"));
				voColumn.add(mapItem.get("MENU_ID"));
				voColumn.add(mapItem.get("MENU_URL"));
				voRow.add(voColumn);
				
			}
			voObject.put("iTotalRecords", listMenubyRole.size());
			voObject.put("iTotalDisplayRecords", listMenubyRole.size());
			voObject.put("aaData",voRow);
			
			db.close();
			out.print(voObject.toJSONString());
    }
    
    public void getDataFromPackge(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	String vaPackageId = request.getParameter("vaRoleId");
		String vaNamePackage = request.getParameter("vaNameRole");
		request.setAttribute("roleId",vaPackageId);
		request.setAttribute("nameRole", vaNamePackage);
		RequestDispatcher rd = request.getRequestDispatcher("CS89001.jsp");
		rd.forward(request, response);
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

}
